package com.xspace.android.xafcommon.adapter;

import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;

import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

public abstract class BasePagerCanDeleteAdapter<T> extends BasePagerAdapter<T> {
	class ItemInfo {
		Object object;

		int position;

		boolean isRemoved;

		public ItemInfo(Object object, int position) {
			super();
			this.object = object;
			this.position = position;
		}
	}

	HashMap<Object, ItemInfo> itemCache = new HashMap<Object, ItemInfo>();

	@Override
	public T getItemById(Long id) {
		try {
			int count = getCount();
			for (int i = 0; i < count; i++) {
				if (id.equals(getItemId(i))) {
					return getData(i);
				}
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public int getItemPosition(Object object) {
		ItemInfo itemInfo = itemCache.get(object);
		if (itemInfo != null) {
			if (itemInfo.isRemoved) {
				itemCache.remove(object);
				return POSITION_NONE;
			}
		}
		return super.getItemPosition(object);
	}

	protected abstract View getView(ViewGroup container, int position);

	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		View object = getView(container, position);
		itemCache.put(object, new ItemInfo(object, position));
		((ViewPager) container).addView(object, 0);
		return object;
	}

	public void removePage(int position) {
		getListData().remove(position);
		setRemoveTag(position);
		notifyDataSetChanged();
	}

	private void setAllRemoveTag() {
		Set<Entry<Object, ItemInfo>> entrySet = itemCache.entrySet();
		if (entrySet != null) {
			for (Entry<Object, ItemInfo> entry : entrySet) {
				entry.getValue().isRemoved = true;
			}
		}
	}

	@Override
	public void setListData(List<T> listData) {
		super.setListData(listData);
		setAllRemoveTag();
	}

	private void setRemoveTag(int position) {
		Set<Entry<Object, ItemInfo>> entrySet = itemCache.entrySet();
		for (Entry<Object, ItemInfo> entry : entrySet) {
			ItemInfo value = entry.getValue();
			int diff = value.position - position;
			if (Math.abs(diff) <= 1) {
				value.isRemoved = true;
			}
		}
	}
}
